﻿using Fizzler.Systems.HtmlAgilityPack;
using Furion.RemoteRequest.Extensions;
using HtmlAgilityPack;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;

namespace apitest.Application.Test.Services
{
    public class M3U8Service 
    {
        string baseUrl = "http://www.hemabi.com";
        public M3U8Service()
        {

        }

        [HttpGet, QueryParameters,NonUnify]
        public async Task<dynamic> Main(string url = "https://www.hemabi.com/play/410798-5-1.html")
        {
            var pageList = await GetPageList(url);
            var res = new List<string>();
            var list = new List<Dictionary<string, string>>();
            foreach (var item in pageList)
            {
                var m3u8 = await GetM3U8Url(item["href"]);
                res.Add($"{item["name"]},{m3u8}");
                var dic = new Dictionary<string, string>
                {
                    { "name", item["name"] },
                    { "src", m3u8 }
                };
                list.Add(dic);
            }
            var filePath = $"123123.txt";
            var txt = res as IEnumerable<string>;
            File.WriteAllLines(filePath, txt);
            return list;
        }

        public async Task<List<Dictionary<string, string>>> GetPageList(string url)
        {
            HtmlDocument doc = new HtmlDocument();
            var headers = new Dictionary<string, string>();
            headers.Add("Sec-Ch-Ua", "1");
            headers.Add("Sec-Ch-Ua-Platform", "Android");
            headers.Add("User-Agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Mobile Safari/537.36");
            string html = await url.SetHeaders(headers).GetAsStringAsync();
            doc.LoadHtml(html);
            var nodes = doc.DocumentNode;
            var list = nodes.QuerySelector(".play-content").QuerySelector(".active");
            var ul = list.FirstChild;
            var li_list = ul.Children();
            var res = new List<Dictionary<string, string>>();
            foreach (var item in li_list)
            {
                var name = item.InnerText;
                var a = item.FirstChild;
                var href = a.GetAttributeValue("href", "");
                var dic = new Dictionary<string, string>();
                dic.Add("name", name);
                dic.Add("href", baseUrl + href);
                res.Add(dic);
            }

            return res;

        }

        public async Task<dynamic> GetHtml(string url)
        {
            return "";
        }

        public async Task<dynamic> GetM3U8Url(string url)
        {
            HtmlDocument doc = new HtmlDocument();
            var headers = new Dictionary<string, string>();
            headers.Add("Sec-Ch-Ua", "1");
            headers.Add("Sec-Ch-Ua-Platform", "Android");
            headers.Add("User-Agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Mobile Safari/537.36");
            string html = await url.SetHeaders(headers).GetAsStringAsync();
            doc.LoadHtml(html);
            var nodes = doc.DocumentNode;
            var script = nodes.QuerySelector(".stui-player__video");
            if (script == null)
            {
                throw new Exception("节点为空");
            }
            var res = script.FirstChild.InnerHtml;
            res = res.Replace("var player_data=", "");
            var obj = JObject.Parse(res);
            var m3u8 = obj["url"].ToString();
            //中文转义
            var begin = "第";
            var end = "集";
            Regex reg = new Regex("(?<=(" + begin + "))[.\\s\\S]*?(?=(" + end + "))", RegexOptions.Multiline | RegexOptions.Singleline);
            var groups = reg.Matches(m3u8).Select(o => o.ToString()).ToList();
            if (groups.Count > 0)
            {
                var num = $"{begin}{groups[0]}{end}";
                var encode = Uri.EscapeUriString(num);
                m3u8 = m3u8.Replace(num, encode);

            }
            return m3u8;
        }


    }
}
